package com.dabai.dbutils.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.util.List;
import java.util.Locale;

/**
 * 原生定位工具类
 * 需要权限
 * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 *
 * 测试 在小米手机上不生效
 */
public class LocationUtils {


    public static Address getAddress(Context context) {

        //获取定位服务
        LocationManager mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //获取当前可用的位置控制器
        List<String> list = mLocationManager.getProviders(true);

        String mProvider = null;
        if (list.contains(LocationManager.GPS_PROVIDER)) {
            //是否为GPS位置控制器
            mProvider = LocationManager.GPS_PROVIDER;//NETWORK_PROVIDER GPS_PROVIDER
        } else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
            //是否为网络位置控制器
            mProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            mProvider = LocationManager.GPS_PROVIDER;//NETWORK_PROVIDER GPS_PROVIDER
        }
        Log.d("DBTAG", "getAddress: " + mProvider);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        Location location = mLocationManager.getLastKnownLocation(mProvider);
        Log.d("DBTAG", "getAddress: "+location );
        if (location != null) {
            Log.d("DBTAG", "getAddress: "+location);
            //用来接收位置的详细信息
            List<Address> result;
            try {
                Geocoder gc = new Geocoder(context, Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
            } catch (Exception e) {
                Log.d("DBTAG", "getAddress: "+e.getMessage());
                return null;
            }
            if(result != null && result.get(0) != null){
                //这块获取到的是个数组我们取一个就好 下面是具体的方法查查API就能知道自己要什么
                return result.get(0);
            }
        } else {
            return null;
        }
        return null;
    }






}
